import React, { Component } from 'react';
import {
  StyleSheet, View, ScrollView, DeviceEventEmitter, TouchableWithoutFeedback, TouchableOpacity, Image, Alert,
} from 'react-native';
import { Text } from 'native-base';
import Icon from 'react-native-vector-icons/AntDesign';
import { produce } from 'immer';
import ZlstIcon from '../../../components/zlst-icons';
import Theme from '../../../native-base-theme/variables/commonColor';
import { UtilToast } from '../../../utils/util-method';
import * as changePartService from '../../../services/changePart';
import { FormTextChoice, FormText, FormSearchChoiceChange, FormInputPop, FormButtonRadio, FormTextarea } from '../../../components';

class ChagePart extends Component {
  static navigationOptions = {
    title: '零部件信息',
    headerStyle: { backgroundColor: Theme.toolbarDefaultBg, borderBottomWidth: 0, elevation: 0 },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  constructor(props) {
    super(props);
    this.state = {
      doWith: [
        { name: '报废', checked: true, value: '0' },
        { name: '修旧', checked: false, value: '1' },
        { name: '拆解', checked: false, value: '2' },
      ],
      advice: '',
      datas: [],
    };
  }

  // 初始化
  componentDidMount() {
    DeviceEventEmitter.addListener('addPartEvent', this.addPartEvent);
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('addPartEvent');
  }

  addPartEvent = (t) => {
    this.addPart(t);
  }

  addPart = (t) => {
    let flag = false; // 表示是否选择过该部件
    this.state.datas.forEach((data, index) => {
      if (data.splitCode == t.splitCode) {
        flag = true;
      }
    });

    if (!flag) {
      this.setState(produce(draft => {
        draft.datas.push(t);
      }));
    } else {
      UtilToast('已选择过该拆分部件', 'danger');
    }
  }

  confirmSub = () => {
    const checkNum = this.getCheckNum();
    if (checkNum == '2' && this.state.datas.length === 0) {
      UtilToast('请添加可用拆解部件', 'danger');
    } else {
      Alert.alert(
        '提示',
        '确定提交',
        [
          { text: '取消', style: 'cancel' },
          {
            text: '确定',
            onPress: () => {
              this.submit();
            },
          },
        ],
      );
    }
  }

  submit = async () => {
    const mParams = this.props.navigation.state.params;
    const checkNum = this.getCheckNum();

    try {
      const materialLots = [];
      this.state.datas.forEach((data, index) => {
        const temp = { materialCode: data.materialCode, materialId: data.materialId, materialName: data.materialName };
        materialLots.push(temp);
      });

      DeviceEventEmitter.emit('showLoading', true);
      const params = {
        commitAction: checkNum,
        advice: this.state.advice,
        equipmentId: mParams.equipmentId,
        failureId: mParams.failureId,
        lotCode: mParams.lotCode,
        materialId: mParams.materialId,
        materialLots,
        operationTime: mParams.operationTime,
        splitCode: mParams.splitCode,
        splitItemId: mParams.splitItemId,
      };
      const data = await changePartService.subChangePart(params);
      DeviceEventEmitter.emit('showLoading', false);
      if (data) {
        UtilToast('提交成功', 'success');
        this.props.navigation.goBack();
        mParams._refresh();
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  doWith = (v) => {
    const doWith = this.state.doWith.map(it => ({
      ...it,
      checked: it.name === v.name,
    }));

    this.setState(produce(draft => {
      draft.doWith = doWith;
    }));
  }

  add = () => {
    const mParams = this.props.navigation.state.params;
    const params = {
      splitItemId: mParams.splitItemId,
      splitCode: mParams.splitCode,
      splitItemDesc: mParams.splitItemDesc,
      materialId: mParams.materialId,
      materialCode: mParams.materialCode,
      materialName: mParams.materialName,
      materialSpecModel: mParams.materialSpecModel,
    };
    this.props.navigation.navigate({ routeName: 'AddChangePart', params });
  }

  _getPartList = () => { // 展示已经选择的拆分备件
    const list = [];
    const { datas } = this.state;
    datas.forEach((item, i) => {
      list.push(
        <View
          key={i}
          style={styles.partContainer}
        >
          <View style={{ flex: 1 }}>
            <Text>
              位置：{`${item.splitDesc}`}
            </Text>
            <Text>
              名称：{`${item.materialName}`}
            </Text>
            <Text>
              型号：{`${item.materialSpecModel}`}
            </Text>
          </View>
          <Icon
            style={{ marginRight: 4 }}
            name="closecircle"
            size={22}
            color="#a4a4a4"
            onPress={() => { this._removeItem(item, i); }}
          />
        </View>,
      );
    });
    return list;
  }

  _removeItem = (item, index) => {
    console.log('need remove item', item, index);
    this.setState(produce(draft => {
      draft.datas.splice(index, 1);
    }));
  }

  getCheckNum = () => {
    let checkNum = '0';
    this.state.doWith.forEach((it) => {
      if (it.checked) {
        checkNum = it.value;
      }
    });
    return checkNum;
  }

  render() {
    const checkNum = this.getCheckNum();

    return (
      <View style={styles.container}>
        <ScrollView style={{ flex: 1 }}>
          <View>
            <View style={styles.title_container}><FormText name="基础信息" fontColor="black" /></View>
            <FormText name="处理方式" />
            <FormButtonRadio datas={this.state.doWith} _click={this.doWith} />
            <FormText name="处理意见" />
            <FormTextarea
              value={this.state.advice}
              _onChangeText={(text) => this.setState({ advice: text })}
            />
            {checkNum == '2' && (
              <View>
                <View style={styles.itemContainer}>
                  <View style={styles.itemLeftContainer}>
                    <Text style={styles.fontStyle}>拆解可用部件</Text>
                  </View>
                  <View style={styles.itemRightContainer}>
                    <TouchableWithoutFeedback onPress={() => this.add()}>
                      <Text style={styles.fontStyle}>新增</Text>
                    </TouchableWithoutFeedback>
                  </View>
                </View>
                <View>
                  {this._getPartList()}
                </View>
              </View>
            )}
          </View>
        </ScrollView>
        <TouchableOpacity style={styles.footer} onPress={() => this.confirmSub()} activeOpacity={0.8}>
          <Image
            source={require('../../../../assets/images/btn-cut-line-xxx.png')}
            style={{ width: '100%', height: 2, alignItems: 'center' }}
            resizeMode="stretch"
            resizeMethod="auto"
          />
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text style={{ color: 'white' }}>提交</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    flexDirection: 'column',
    backgroundColor: Theme.myPrimary,
  },
  title_container: {
    width: '100%',
    backgroundColor: 'white',
    borderLeftWidth: 8,
    borderLeftColor: '#4f6fe3',
    // borderRadius: 4,
  },
  header_container: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
  },
  partContainer: {
    backgroundColor: 'white',
    borderRadius: 8,
    marginLeft: 8,
    marginRight: 8,
    marginTop: 8,
    padding: 8,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerText: {
    color: 'white',
    fontWeight: 'bold',
  },
  backBtn: {
    paddingLeft: 8,
    paddingRight: 8,
    paddingTop: 16,
    paddingBottom: 16,
  },
  itemContainer: {
    padding: 8,
    marginTop: 8,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'white',
    borderLeftWidth: 8,
    borderLeftColor: '#4f6fe3',
  },
  itemLeftContainer: {
    flex: 1,
  },
  itemRightContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  fontStyle: {
    fontSize: Theme.myNormalFontSize,
    color: 'black',
  },
  footer: {
    width: '100%',
    flexDirection: 'column',
    backgroundColor: Theme.myPrimary,
    height: 48,
  },
});

export default ChagePart;
